
const { execSql } = require('../dbop/mysql')
// connection.connect();
async function addUser(data) {
    //userlist userid  ???
    var addSql = 'INSERT INTO users(username,pwd) VALUES(?,?)';
    var addSqlParams = [data.username, data.pwd];
    //增
    const result = await execSql(addSql, addSqlParams);
  //  connection.query(addSql, addSqlParams)



    //更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });

    // connection.end()

}



function updateUser(data) {
    //??  update where id=data.id
}


async function deleteUser(delid) {
    //??  update where id=data.id
    var delSql = 'delete from users where id=?';
    var delSqlParams = [delid];
    //增
    const result = await execSql(delSql, delSqlParams);
    return 'del ok!!!'
}

async function getUsers() {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用

    const sql = "select * from users"
    // const mypromise = new Promise((resolve, reject) => {

    //     connection.query(sql, function (err, result) {
    //         if (err) {
    //             reject(err)
    //             return;
    //         }

    //         resolve(result)
    //     })

    // })
    const result = await execSql(sql);
    const myarray = JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}


async function getUser(data) {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql = "select * from users where username=? and pwd=?"

    var sqlParams = [data.username, data.pwd];
    const result = await execSql(sql, sqlParams);
    const myarray = JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray.length > 0

    //存到缓存，后面从缓存里面获取
}
/*
async function addUser(data){

   const tlist=await getUsers()

   tlist.push(data)

   const jstr=JSON.stringify(tlist)
   const key="users"
   client.set(key,jstr)
}*/


module.exports = {
    getUsers, addUser, deleteUser,getUser
}


